import {
  BadRequestException,
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Inject,
  Post,
  Req,
} from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { UserService } from './user.service';
import { Public } from '../auth/auth.guard';
import { JwtService } from '@nestjs/jwt';
import { ApiOperation, ApiTags } from '@nestjs/swagger';

@ApiTags('用户模块')
@Controller('user')
export class UserController {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  @ApiOperation({ summary: '获取手机验证码' })
  @Public()
  @Post('phone_code')
  async getPhoneCode(@Body('phone') data: any) {
    console.log(data);
    const code = Math.random().toString().slice(2, 8);
    await this.cacheManager.set(data, code, 60 * 5000);
    return {
      code,
    };
  }
  @ApiOperation({ summary: '用户登录信息' })
  @Get('user_info')
  async checkLogin(@Req() req: any) {
    const user = req.user;
    if (!user.phone) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    const queryUser = await this.userService.findOne(user.phone);
    if (!queryUser) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    return queryUser;
  }

  @ApiOperation({ summary: '收藏文章' })
  @Post('/store')
  async store(@Req() req: any, @Body('id') id: any) {
    if (!id) throw new BadRequestException('id不能为空');
    const store = await this.userService.createStore(id, req.user.sub);
    if (!store) {
      throw new HttpException('创建失败', HttpStatus.BAD_REQUEST);
    }
    return store;
  }

  @ApiOperation({ summary: '取消收藏' })
  @Post('remove_store')
  async removeStore(@Req() req: any, @Body('id') id: any) {
    if (!id) throw new BadRequestException('id不能为空');
    const store = await this.userService.removeStore(id, req.user.sub);
    if (!store) {
      throw new HttpException('删除失败', HttpStatus.BAD_REQUEST);
    }
    return store;
  }

  @ApiOperation({ summary: '收藏列表' })
  @Get('store_list')
  async getStoreList(@Req() req: any) {
    return await this.userService.queryStoreList(req.user.sub);
  }

  @ApiOperation({ summary: '用户信息更新' })
  @Post('user_update')
  async userUpdate(
    @Req() req: any,
    @Body('nickname') nickname: string,
    @Body('url') url: string,
  ) {
    return await this.userService.queryUserUpdate(req.user.sub, nickname, url);
  }
}
